import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

// 更新回答
export async function PUT(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { id } = params
    const { content, isAccepted } = await req.json()

    // 检查回答是否存在
    const answer = await prisma.forumAnswer.findUnique({
      where: { id },
      include: {
        question: true,
      },
    })

    if (!answer) {
      return NextResponse.json({ message: '回答不存在' }, { status: 404 })
    }

    // 检查权限
    // 只有回答的作者可以修改内容
    if (content && answer.authorId !== session.user.id) {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    // 只有问题的作者、教师或管理员可以接受回答
    if (isAccepted !== undefined) {
      const question = await prisma.forumQuestion.findUnique({
        where: { id: answer.questionId },
      })

      if (!question || (question.authorId !== session.user.id && session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER')) {
        return NextResponse.json({ message: '权限不足' }, { status: 403 })
      }

      // 如果接受了这个回答，需要将其他回答设为未接受，同时更新问题为已解决
      if (isAccepted) {
        await prisma.forumAnswer.updateMany({
          where: {
            questionId: answer.questionId,
            id: { not: id },
          },
          data: {
            isAccepted: false,
          },
        })

        // 更新问题为已解决
        await prisma.forumQuestion.update({
          where: { id: answer.questionId },
          data: {
            isSolved: true,
          },
        })
      }
    }

    // 准备更新数据
    const updateData: any = {}
    if (content) updateData.content = content
    if (isAccepted !== undefined) updateData.isAccepted = isAccepted

    // 更新回答
    const updatedAnswer = await prisma.forumAnswer.update({
      where: { id },
      data: updateData,
      include: {
        author: {
          select: {
            id: true,
            name: true,
            role: true,
          },
        },
      },
    })

    return NextResponse.json({
      message: '回答更新成功',
      answer: updatedAnswer,
    })
  } catch (error) {
    console.error('更新回答失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
}

// 删除回答
export async function DELETE(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { id } = params

    // 检查回答是否存在
    const answer = await prisma.forumAnswer.findUnique({
      where: { id },
    })

    if (!answer) {
      return NextResponse.json({ message: '回答不存在' }, { status: 404 })
    }

    // 检查权限（只有作者或管理员可以删除回答）
    if (answer.authorId !== session.user.id && session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    // 如果是已接受的答案，需要将问题标记为未解决
    if (answer.isAccepted) {
      await prisma.forumQuestion.update({
        where: { id: answer.questionId },
        data: {
          isSolved: false,
        },
      })
    }

    // 删除回答
    await prisma.forumAnswer.delete({
      where: { id },
    })

    return NextResponse.json({ message: '回答已删除' })
  } catch (error) {
    console.error('删除回答失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
} 